package com.itlong.cloud.controller.system;

import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.iottp.IIotTpSmsServiceClient;
import com.itlong.cloud.project.property.IPropertyPayPasswordServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      物业支付密码控制器
 * </desc>
 *
 * @createDate 2018/09/25
 */
@RestController
@RequestMapping("/system/payPassword")
@RefreshScope
public class PropertyPayPasswrodController {
    @Autowired
    IPropertyPayPasswordServiceClient iPropertyPayPasswordServiceClient;

    @Autowired
    IIotTpSmsServiceClient iIotTpSmsServiceClient;

    @Autowired
    RedisService redisService;

    @Value("${" + PlatformConstants.PROPERTY_USER_TOKEN_KEY + "}")
    String userTokenKey;

    /**
     * <desc>
     *      修改支付密码
     * </desc>
     *
     * @param projectId
     * @param oldPassword
     * @param newPassword
     * @param confirmPassword
     * @return
     * @author Jiaqi.X
     * @createDate 2018/09/25
     */
    @PostMapping(path = "/update")
    @LoggerInfo(operateDesc = LogDescConstant.UPDATE_PAYMENT_PASSWORD_LOG_DESC)
    @ResponseBody
    @AuthAccessRequired
    public Object update(String projectId,String oldPassword,String newPassword,String confirmPassword){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            oldPassword = request.getAttribute("oldPassword") == null ? null : request.getAttribute("oldPassword").toString();
            newPassword = request.getAttribute("newPassword") == null ? null : request.getAttribute("newPassword").toString();
            confirmPassword = request.getAttribute("confirmPassword") == null ? null : request.getAttribute("confirmPassword").toString();
            ProjectPO projectPO = iPropertyPayPasswordServiceClient.getProjectInfo(projectId);
            //解密密码
            oldPassword = UserTokenUtil.getPassword(oldPassword, userTokenKey);
            newPassword =  UserTokenUtil.getPassword(newPassword, userTokenKey);
            confirmPassword = UserTokenUtil.getPassword(confirmPassword, userTokenKey);
            if(StringUtils.isBlank(projectPO.getPayPassword())){
                return new MessageVO(PropertyErrorCodeEnum.PAY_PASSWORD_ERROR.getErrorCode());
            }
            if(!projectPO.getPayPassword().equals(oldPassword)){
                return new MessageVO(PropertyErrorCodeEnum.PAY_PASSWORD_ERROR.getErrorCode());
            }
            if(!newPassword.equals(confirmPassword)){
                return new MessageVO(PropertyErrorCodeEnum.PAY_PASSWORD_EXISTS.getErrorCode());
            }
            if(newPassword.equals(projectPO.getPayPassword())){
                return new MessageVO(PropertyErrorCodeEnum.PAY_PASSWORD_ALIKE.getErrorCode());
            }
            iPropertyPayPasswordServiceClient.updatePayPassword(projectId,newPassword);
            messageVO = new MessageVO(projectPO.getProjectId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_支付密码管理update】修改支付密码失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      发送验证码
     * </desc>
     *
     * @param phoneNum
     *
     * @return MessageVO 标准格式化响应结果
     * @author Jiaqi.X
     * @createDate 2018/09/20
     */
    @PostMapping(path = "/sendMessage")
    @ResponseBody
    public Object sendMessage(String phoneNum,String projectId){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            phoneNum = request.getAttribute("phoneNum") == null ? null : request.getAttribute("phoneNum").toString();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            ProjectPO projectPO = iPropertyPayPasswordServiceClient.getProjectInfo(projectId);
            if(StringUtils.isBlank(projectPO.getBankPhoneNum())){
                return new MessageVO(PropertyErrorCodeEnum.PAY_PASSWORD_NULL_ERROR.getErrorCode());
            }
            if(!phoneNum.equals(projectPO.getBankPhoneNum())){
                return new MessageVO(PropertyErrorCodeEnum.BANK_PHONE_ERROR.getErrorCode());
            }
            String smsCode = NumberHandlerUtil.randomNum(6);
            while (smsCode.substring(0,1).equals("0")){
                smsCode = NumberHandlerUtil.randomNum(6);
            }
            String content = "验证码:" + smsCode + ",该验证码将在30分钟后失效.";
            Map<String, Object> map = (HashMap) redisService.getObject(RedisConstant.PAY_PASSWORD_PHONE_SEND_MESSAGE_COUNT + phoneNum, HashMap.class);
            if (map == null) {
                map = new HashMap<>();
            }
            Integer count = (Integer) map.get("count");
            if (count == null) {
                count = 1;
            } else {
                count++;
            }
            if (count > 3) {
                return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_COUNT_SURPASS.getErrorCode());
            } else {
                map.put("count", count);
                map.put("smsCode", smsCode);
                iIotTpSmsServiceClient.sendSmsCodeByPhone(phoneNum, content);
                redisService.set(RedisConstant.PAY_PASSWORD_PHONE_SEND_MESSAGE_COUNT + phoneNum, RedisConstant.PAY_PASSWORD_PHONE_SEND_MESSAGE_COUNT_TIME, map);
                //保存验证码
                redisService.set(RedisConstant.PAY_PASSWORD_PHONE_SEND_MESSAGE_KEY + phoneNum,RedisConstant.PAY_PASSWORD_PHONE_SEND_MESSAGE_CACHE_TIME,smsCode);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【物业_系统_银行卡管理addBankSendMessage】发送验证码失败", e);
        }
    }

    /**
     * <desc>
     *      验证银行卡信息
     * </desc>
     *
     * @param projectId
     * @param userName
     * @param bankCardNo
     * @param phoneNum
     * @param validCode
     * @return
     * @author Jiaqi.X
     * @createDate 2018/09/25
     */
    @PostMapping(path = "/checkBankInfo")
    @ResponseBody
    public Object checkBankInfo(String projectId,String userName,String bankCardNo,String phoneNum,String validCode){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            userName = request.getAttribute("userName") == null ? null : request.getAttribute("userName").toString();
            bankCardNo = request.getAttribute("bankCardNo") == null ? null : request.getAttribute("bankCardNo").toString();
            phoneNum = request.getAttribute("phoneNum") == null ? null : request.getAttribute("phoneNum").toString();
            validCode = request.getAttribute("validCode") == null ? null : request.getAttribute("validCode").toString();
            //校验银行账户信息
            Integer check = iPropertyPayPasswordServiceClient.checkBankInfo(projectId,userName,bankCardNo);
            if(check > 0){
                //检验验证码
                //获取缓存中的验证码
                String smsCode = (String) redisService.getObject(RedisConstant.PAY_PASSWORD_PHONE_SEND_MESSAGE_KEY + phoneNum, String.class);

                if(StringUtils.isBlank(smsCode)){
                    return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_EXISTS.getErrorCode());
                }
                if(!smsCode.equals(validCode)){
                    return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_SEND_MESSAGE_ERROR.getErrorCode());
                }

                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }else{
                return new MessageVO(PropertyErrorCodeEnum.BANK_CARD_NOT_EXISTS.getErrorCode());
            }
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_支付密码管理update】修改支付密码失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      验证银行卡信息成功后修改支付密码
     * </desc>
     *
     * @param projectId
     * @param payPassword
     * @param confirmPassword
     * @return
     * @author Jiaqi.X
     * @createDate 2018/09/25
     */
    @PostMapping(path = "/checkBankInfoUpdatePassword")
    @LoggerInfo(operateDesc = LogDescConstant.UPDATE_PAYMENT_PASSWORD_LOG_DESC)
    @ResponseBody
    public Object checkBankInfoUpdatePassword(String projectId,String payPassword,String confirmPassword){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            payPassword = request.getAttribute("payPassword") == null ? null : request.getAttribute("payPassword").toString();
            confirmPassword = request.getAttribute("confirmPassword") == null ? null : request.getAttribute("confirmPassword").toString();
            ProjectPO projectPO = iPropertyPayPasswordServiceClient.getProjectInfo(projectId);
            if(!payPassword.equals(confirmPassword)){
                return new MessageVO(PropertyErrorCodeEnum.PAY_PASSWORD_EXISTS.getErrorCode());
            }
            iPropertyPayPasswordServiceClient.updatePayPassword(projectId,payPassword);
            messageVO = new MessageVO(projectPO.getProjectId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【物业_系统_支付密码管理checkBankInfoUpdatePassword】修改支付密码失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      根据开户账户名和开户账号查询绑定手机号
     * </desc>
     *
     * @param projectId
     * @return
     * @author Jiaqi.X
     * @createDate 2018/09/25
     */
    @PostMapping(path = "/checkBankInfoGetPhoneNum")
    @ResponseBody
    public Object checkBankInfoGetPhoneNum(String projectId){
        MessageVO messageVO;
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            ProjectPO projectPO = iPropertyPayPasswordServiceClient.getProjectInfo(projectId);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),
                    StringUtils.isNotBlank(projectPO.getBankPhoneNum()) ?
                            projectPO.getBankPhoneNum().substring(0,3)+"****"+projectPO.getBankPhoneNum().substring(7,projectPO.getBankPhoneNum().length()) : "");
        }catch (Exception e){

            throw new DataAccessException("【物业_系统_根据开户账户名和开户账号查询绑定手机号checkBankInfoGetPhoneNum】修改支付密码失败",e);
        }
        return messageVO;
    }

}
